<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="食材类型" prop="foodTypeName">
        <el-input
          v-model="queryParams.foodTypeName"
          placeholder="请输入食材类型"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="启用状态" prop="isEnabled">
        <el-select
          v-model="queryParams.isEnabled"
          placeholder="请选择状态"
          clearable
        >
          <el-option
            label="未启用"
            value="0"
          ></el-option>
          <el-option
            label="已启用"
            value="1"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['manage:foodType:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Sort"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="foodTypeList"
      row-key="foodTypeId"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column label="序号" align="center">
        <template #default="scope">
          {{ scope.row.index }}
        </template>
      </el-table-column>
      <el-table-column label="食材类型" prop="foodTypeName" width="100" />
      <el-table-column label="图片" align="center" prop="imageUrl">
        <template #default="scope">
          <image-preview :src="scope.row.imageUrl" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="存储条件" align="center" prop="storageCondition" />
      <el-table-column label="描述" align="center" prop="remark" show-overflow-tooltip />
      <el-table-column label="是否启用" align="center" prop="isEnabled">
        <template #default="scope">
          <el-switch
            v-model="scope.row.isEnabled"
            class="ml-2"
            inline-prompt
            style="--el-switch-off-color: #F56C6C"
            size="large"
            active-text="已启用"
            inactive-text="未启用"
            :active-value="1"
            :inactive-value="0"
            @click="updateFoodTypeStatus(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['manage:foodType:edit']">修改</el-button>
          <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['manage:foodType:add']">新增</el-button>
          <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['manage:foodType:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改食材类型对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="foodTypeRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="食材类型" prop="foodTypeName">
          <el-input v-model="form.foodTypeName" placeholder="请输入食材类型" />
        </el-form-item>
        <el-form-item label="食材图片" prop="imageUrl">
          <image-upload v-model="form.imageUrl" :limit="1" />
        </el-form-item>
        <el-form-item label="上级类型" prop="parentId" v-if="form.parentId !== 0">
          <el-tree-select
            v-model="form.parentId"
            :data="foodTypeOptions"
            :props="{ value: 'foodTypeId', label: 'foodTypeName', children: 'children' }"
            value-key="foodTypeId"
            placeholder="选择上级类型"
            check-strictly
            clearable
          />
          <div class="form-item-tip">此项选填：如没有上级类型，可不填</div>
        </el-form-item>
        <el-form-item label="存储条件" prop="storageCondition">
          <el-input v-model="form.storageCondition" placeholder="请输入存储条件" />
        </el-form-item>
        <el-form-item label="食材描述" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="FoodType">
import { listFoodType, getFoodType, delFoodType, addFoodType, updateFoodType } from "@/api/manage/foodType";

const { proxy } = getCurrentInstance();

const foodTypeList = ref([]);
const foodTypeOptions = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const title = ref("");
const isExpandAll = ref(false);
const refreshTable = ref(true);

const data = reactive({
  form: {},
  queryParams: {
    foodTypeName: null,
    isEnabled: null
  },
  rules: {
    foodTypeName: [
      { required: true, message: "食材类型名称不能为空", trigger: "blur" }
    ],
    storageCondition: [
      { required: true, message: "存储条件不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

// 递归生成序号的方法
function generateIndex(data, parentIndex = '') {
  return data.map((item, index) => {
    const currentIndex = parentIndex ? `${parentIndex}-${index + 1}` : `${index + 1}`;
    item.index = currentIndex;
    
    if (item.children && item.children.length > 0) {
      item.children = generateIndex(item.children, currentIndex);  // 递归处理子节点
    }
    return item;
  });
}

/** 查询食材类型列表 */
function getList() {
  loading.value = true;
  listFoodType(queryParams.value).then(response => {
    const formattedData = proxy.handleTree(response.data, "foodTypeId", "parentId");
    foodTypeList.value = generateIndex(formattedData);  // 生成序号
    loading.value = false;
  });
}

/** 查询食材类型下拉树结构 */
function getTreeselect() {
  listFoodType().then(response => {
    // foodTypeOptions.value = [];
    // const data = { foodTypeId: 0, foodTypeName: '食材类型', children: [] };
    // data.children = proxy.handleTree(response.data, "foodTypeId", "parentId");
    // foodTypeOptions.value.push(data);
    foodTypeOptions.value = proxy.handleTree(response.data, "foodTypeId", "parentId");
  });
}
	
// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    foodTypeId: null,
    foodTypeName: null,
    parentId: null,
    remark: null,
    storageCondition: null,
    imageUrl: null,
    isEnabled: null
  };
  proxy.resetForm("foodTypeRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd(row) {
  reset();
  getTreeselect();
  if (row != null && row.foodTypeId) {
    form.value.parentId = row.foodTypeId;
  }
  open.value = true;
  title.value = "添加食材类型";
}

/** 展开/折叠操作 */
function toggleExpandAll() {
  refreshTable.value = false;
  isExpandAll.value = !isExpandAll.value;
  nextTick(() => {
    refreshTable.value = true;
  });
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset();
  await getTreeselect();
  if (row != null) {
    form.value.parentId = row.parentId;
  }
  getFoodType(row.foodTypeId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改食材类型";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["foodTypeRef"].validate(valid => {
    if (valid) {
      if (form.value.foodTypeId != null) {
        updateFoodType(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addFoodType(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _foodTypeIds = row.foodTypeId || ids.value;
  const delName = _foodTypeIds.length >= 1 ? '选中的食材类型' : row.foodTypeName
  proxy.$modal.confirm('确定要删除' + delName + '吗？').then(function() {
    return delFoodType(row.foodTypeId);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 修改类型启用状态  **/
function updateFoodTypeStatus(row) {
  if(row != null) {
    const _isEnabled = row.isEnabled == false ? 0 : 1;
    const data = {
      foodTypeId: row.foodTypeId,
      isEnabled: _isEnabled
    }
    updateFoodType(data).then(response => {
      getList();
      if(data.isEnabled == 0) {
        proxy.$modal.msgSuccess("禁用成功");
      } else {
        proxy.$modal.msgSuccess("启用成功");
      }
    });
  }
}



getList();
</script>

<style scoped>
.form-item-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}
</style>
